﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using Microsoft.Xna.Framework;
using System.Xml.Serialization;
using Kristall.Engine;
using Kristall.Engine.Scripts;

namespace Kristall.MyGame.Scripts
{
    public class PlatformScript : Script
    {
        [XmlIgnore]
        private List<Vector2> _waypoints = new List<Vector2>();

        [XmlIgnore]
        public int NumberOfWaypoints
        {
            get
            {
                return Waypoints.Count;
            }
        }

        /// <summary>
        /// Have to use point instead of vector2, since propertygrid wont cooperate with xna types
        /// </summary>
        public List<System.Drawing.PointF> Waypoints
        {
            get;
            set;
        }

        public bool Loop { get; set; }

        public float Speed { get; set; }

        int _currentWaypoint = 0;

        private AABB _aabb;

        public PlatformScript() : base()
        {
            Waypoints = new List<System.Drawing.PointF>();
            Speed = 100f;
            Loop = true;
        }

        public override void Load(Level level, AABB aabb)
        {
            base.Load(level, aabb);

            _aabb = aabb;

            Waypoints.ForEach(v => _waypoints.Add(new Vector2(v.X, v.Y)));
        }

        public override void Update(float dt)
        {

            base.Update(dt);

            if (!_waypoints.Any() || Enabled == false)
                return;

            //did we reach the waypoint?
            float distance = Vector2.Distance(_aabb.Position, _waypoints[_currentWaypoint]);

            if (distance < 0.01f)
            {
                _currentWaypoint++;
                _aabb.Velocity = Vector2.Zero;

                if (_currentWaypoint >= _waypoints.Count)
                { 
                    _currentWaypoint = 0;

                    if (!Loop)
                    { 
                        Enabled = false;
                        return;
                    }
                }
            }

            //move towards waypoint
            Vector2 direction = _waypoints[_currentWaypoint] - _aabb.Position;
            if (direction != Vector2.Zero)
            { 
                direction.Normalize();

                //how far can we get in this update?
                _aabb.Velocity = direction * Speed;
                Vector2 distanceToMove = _aabb.Velocity * dt;

                float temp = distanceToMove.Length();
                if (temp >= distance) //If we can move the whole distance or more
                {
                    _aabb.Velocity = direction * distance / dt; // direction* Speed; //set velocity to distance
                }

                //update position
                _aabb.Position += _aabb.Velocity * dt;
            }
        }
    }
}
